import projects from '../models/project'
import Conflicted from '../errors/conflicted'
import NotFound from '../errors/NotFoundError'
import BadRequest from '../errors/badReques'
import { CREATED_CODE } from '../errors/statusCode'

export const createProject = (req, res, next) => {
  const {
    title,
    code,
    manager,
    from,
    to,
    comment,
    config,
    boardLink,
    isActive,
    responsibleEmployee
  } = req.body;
  projects.create({
    title,
    code,
    manager,
    from: new Date(from),
    to: new Date(to),
    comment,
    config,
    boardLink,
    isActive,
    responsibleEmployee
  })
    .then((project) => res.send(project))
    .catch((evt) => {
      if (evt.name === 'ValidationError') {
        next(
          new BadRequest(
            'Переданы некорректные данные при создании карточки проекта',
          ),
        );
      } else {
        next(evt)
      }
    })
}
export  const getProject = (req, res, next) => {
  projects.find({isActive: true}).populate('manager').populate('responsibleEmployee')
    .then((project) => {
      res.send(project);
    })
    .catch(next)
}

export const updateProject = (req, res, next) => {
  const {
    title,
    code,
    manager,
    from,
    to,
    comment,
    config,
    boardLink,
    isActive,
    responsibleEmployee
  } = req.body;
  projects.findByIdAndUpdate(
    req.params.projectId,
    {
      title,
      code,
      manager,
      from: new Date(from),
      to: new Date(to),
      comment,
      config,
      boardLink,
      isActive,
      responsibleEmployee
    },
    {
      new: true,
      runValidators: true,
    },
  )
    .orFail(() => {
      throw new NotFound('Сотрудник с указанным _id не найден')
    })
    .then((project) => {
      res.send(project)
    })
    .catch((evt) => {
      if (evt.code === 11000) {
        next(new Conflicted('Такое задание уже существует'))
      } else if (evt.name === 'ValidationError') {
        next(new BadRequest('Переданы некорректные данные при удалении проекта'))
      } else {
        next(evt)
      }
    })
}

export const deleteProject = (req, res, next) => {
  const { } = req.body;
  projects.findByIdAndUpdate(
    req.params.projectId,
    {
      isActive: false,
    },
    {
      new: true,
      runValidators: true,
    },
  )
    .orFail(() => {
      throw new NotFound('Сотрудник с указанным _id не найден')
    })
    .then((project) => {
      res.send(project)
    })
    .catch((evt) => {
      if (evt.code === 11000) {
        next(new Conflicted('Такое задание уже существует'))
      } else if (evt.name === 'ValidationError') {
        next(new BadRequest('Переданы некорректные данные при обновлении проекта'))
      } else {
        next(evt)
      }
    })
}
